<template>
  <div>
    <div>
      <div>
        <n-form ref="form" :model="model" :rules="rules">
          <n-form-item :label="$t('user.login.username')" path="username">
            <n-input v-model:value="model.username" @keydown.enter.prevent />
          </n-form-item>
          <n-form-item :label="$t('user.login.password')" path="password">
            <n-input v-model:value="model.password" type="password" @keydown.enter.prevent />
          </n-form-item>
          <n-button :loading="pushing" style="width: 100%" type="primary" @click="submit">
            {{ $t("common.actions.login") }}
          </n-button>
        </n-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import axiosHttp from "axios";
import { useCookies } from "vue3-cookies";
import { NButton, NForm, NFormItem, NInput, useMessage } from "naive-ui";
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const rules = {
  username: [{ required: true, message: t("user.login.validate.username") }],
  password: [{ required: true, message: t("user.login.validate.password") }],
};

const { cookies } = useCookies();
const axios = axiosHttp.create({ validateStatus: () => true });
const message = useMessage();

const router = useRouter();
const route = useRoute();

const pushing = ref(false);
const form = ref(null);
const model = reactive({
  username: "",
  password: "",
  remember: false,
});

function submit() {
  form.value?.validate((error) => {
    if (!error) {
      pushing.value = true;
      axios
        .post("/api/authenticate", {
          username: model.username,
          password: model.password,
        })
        .then((response) => {
          if (response.status === 201) {
            message.success(t('user.login.messages.success'));
            console.log(
              "[SAFETY] Successfully logged in, there is your JWT, please do not share to anyone, just for client development and test: ",
              response.data["token"]
            );
            if (model.remember) {
              // Set cookies until access token expires
              cookies.set("access_token", response.data["token"], "30d");
            } else {
              // Set cookies until user close brozwer expires
              cookies.set("access_token", response.data["token"], 0);
            }
            if (route.params["redirect"]) {
              router.push(route.params["redirect"]).then(() => router.go());
            } else {
              router.push({ name: "introduce" }).then(() => router.go());
            }
          } else if (response.status === 401) {
            message.warning(t('user.login.messages.invalid'));
          } else {
            message.error(t('common.messages.request-unknown-error'));
          }
          pushing.value = false;
        })
        .catch((error) => {
          message.error(t('common.messages.request-unknown-error'));
          message.error(error.message);
          pushing.value = false;
        });
    }
  });
}
</script>
